import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

/**
 * 用户状态管理
 */
export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref<{
    id: string
    name: string
    email: string
    phone?: string
    avatar?: string
    role: string
    permissions: string[]
  } | null>(null)

  const users = ref<Array<any>>([])
  const loading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!user.value)
  const hasUser = computed(() => !!user.value)
  const userRole = computed(() => user.value?.role || '')
  const userPermissions = computed(() => user.value?.permissions || [])

  // 方法
  const setUser = (userData: any) => {
    user.value = userData
  }

  const clearUser = () => {
    user.value = null
  }

  const updateUser = (updates: Partial<typeof user.value>) => {
    if (user.value) {
      user.value = { ...user.value, ...updates }
    }
  }

  const hasPermission = (permission: string): boolean => {
    return userPermissions.value.includes(permission)
  }

  const hasRole = (role: string): boolean => {
    return userRole.value === role
  }

  const hasAnyRole = (roles: string[]): boolean => {
    return roles.includes(userRole.value)
  }

  const hasAllPermissions = (permissions: string[]): boolean => {
    return permissions.every(permission => hasPermission(permission))
  }

  const hasAnyPermission = (permissions: string[]): boolean => {
    return permissions.some(permission => hasPermission(permission))
  }

  const setUsers = (userList: any[]) => {
    users.value = userList
  }

  const addUser = (userData: any) => {
    users.value.push(userData)
  }

  const updateUserInList = (userId: string, updates: any) => {
    const index = users.value.findIndex(u => u.id === userId)
    if (index > -1) {
      users.value[index] = { ...users.value[index], ...updates }
    }
  }

  const removeUserFromList = (userId: string) => {
    const index = users.value.findIndex(u => u.id === userId)
    if (index > -1) {
      users.value.splice(index, 1)
    }
  }

  const setLoading = (value: boolean) => {
    loading.value = value
  }

  return {
    // 状态
    user,
    users,
    loading,
    
    // 计算属性
    isLoggedIn,
    hasUser,
    userRole,
    userPermissions,
    
    // 方法
    setUser,
    clearUser,
    updateUser,
    hasPermission,
    hasRole,
    hasAnyRole,
    hasAllPermissions,
    hasAnyPermission,
    setUsers,
    addUser,
    updateUserInList,
    removeUserFromList,
    setLoading
  }
})